<?php

namespace app\models\system;

use app\models\Images;
use Yii;

/**
 * This is the model class for table "set_wx".
 *
 * @property int $id
 * @property string $app_id
 * @property string $app_secret
 * @property string $wx_secret
 * @property string $wx_id
 * @property string $token
 * @property string $aes_key
 * @property string $pay_key
 * @property string $mch_id
 * @property int $image_id 公众号二维码图片
 */
class SetWx extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'set_wx';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['image_id'], 'integer'],
            [['app_id'], 'string', 'max' => 50],
            [['app_secret'], 'string', 'max' => 100],
            [['token', 'aes_key', 'pay_key', 'mch_id'], 'string', 'max' => 255],

            [['wx_id', 'wx_secret'], 'safe']
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'app_id' => 'App ID',
            'app_secret' => 'App Secret',
            'token' => 'Token',
            'aes_key' => 'Aes Key',
            'pay_key' => 'Pay Key',
            'mch_id' => 'Mch ID',
            'image_id' => 'Image ID',
        ];
    }

    public static function getLastOne($is_array = true)
    {
        if ($is_array) {
            $model = self::find()
                ->orderBy(['id' => SORT_DESC])
                ->with(['image'])
                ->asArray()
                ->one();
        } else {
            $model = self::find()
                ->orderBy(['id' => SORT_DESC])
                ->one();
        }

        if (!$model) {
            $model = new self();
        }

        return $model;
    }

    public static function saveData($data)
    {
        $model = self::find()
            ->orderBy(['id' => SORT_DESC])
            ->one();

        if ($model->load(['SetWx' => $data]) && $model->save()) {
            return true;
        }
    }

    public function getImage()
    {
        return $this->hasOne(Images::class, ['id' => 'image_id']);
    }
}
